import React, { useState,useEffect } from 'react'
import { Carousel,Tag,Toast,Modal  } from 'antd-mobile'
import {Map,Marker} from 'react-bmapgl'
import { connect } from 'react-redux'

import Navbar from '../../components/Navbar'
import HouseList from '../../components/HouseList'
import { BASEURL,reqHouseDetail,reqAddCollected,reqCheckIsCollected,reqDeleteCollected } from '../../api'
import { records_action,user_action } from '../../utils'
import { addRecord,resetUserData,removeRecord } from '../../redux/actions'

import './index.scss'

const alert=Modal.alert

export default connect(state=>({user:state.user}),{addRecord,resetUserData,removeRecord})(function Detail(props) {
  const {user,history}=props
  const {id}=props.location.state

  const [data, setData] = useState(null)
  const [collectState, setCollectState] = useState({active:false,isCollected:false})

  const icons={
    "电视":'iconfont icon-vid', 
    "冰箱":'iconfont icon-ref', 
    "洗衣机":'iconfont icon-wash', 
    "空调":'iconfont icon-air', 
    "热水器":'iconfont icon-heater', 
    "沙发":'iconfont icon-sofa', 
    "衣柜":'iconfont icon-wardrobe', 
    "天然气":'iconfont icon-gas',
    "暖气":'iconfont icon-Heat',
    "宽带":'iconfont icon-broadband',
  }

  const guessData=[
    {
      desc: "二室/111/南|北/翠盈嘉园",
      houseCode: "5cc46a921439630e5b439611",
      houseImg: "/newImg/7bklfc58n.jpg",
      price: 1100,
      tags: ["集中供暖"],
      title: "翠盈嘉园 2室2厅 1100元"
    },{
      desc: "三室/84/东南/汉森吉祥龙",
      houseCode: "5cc4a1d31439630e5b50205c",
      houseImg: "/newImg/7bklfc58n.jpg",
      price: 18000,
      tags: ["近地铁", "随时看房"],
      title: "深圳湾 吉祥龙花园 大三房精装修 业主急租~"
    },{
      desc: "三室/84/南/白沙地",
      houseCode: "5cc478231439630e5b46bf22",
      houseImg: "/newImg/7bjm91d3c.jpg",
      price: 1800,
      tags: ["近地铁"],
      title: "白沙地 3室2厅 1800元"
    }
  ]

  const checkLogin=()=>{
    if(user)return true
    return false
  }

  const MyAlert=()=>{
    alert('提示','登录之后才能收藏房源,是否去登录?',[
      {text:'取消',onPress:null},
      {text:<span style={{color:'#21b97a'}}>去登陆</span>,onPress:()=>history.replace('/login',{id})},
    ])
  }

  const controllers=[
    {id:1,icon:'iconfont icon-coll',name:'收藏',style:{color:collectState.isCollected?'#ff4f00':''},action:()=>checkLogin()?setCollectState({...collectState,active:true}):MyAlert()},
    {id:2,icon:'',name:'在线咨询',style:{},action:()=>Toast.info('暂不支持在线咨询',1,()=>{},false)},
    {id:3,icon:'',name:'电话预约',style:{backgroundColor:'#21b97a',color:'#fff'},action:()=>Toast.info('暂不支持电话预约',1,()=>{},false)},
  ]

  useEffect(()=>{
    const {addRecord,resetUserData,removeRecord}=props
    const checkLogin=()=>{
      if(user)return true
      return false
    }
    async function getDetail(id){ //获取房屋数据
      let res=await reqHouseDetail(id)
      setData(res.body)
      if(!user)return
      const {get,add}=records_action
      if(get()&&get().findIndex(i=>i.houseCode===id)===-1){
        addRecord(res.body)
        add(res.body)
      }
    }
    async function checkIsCollected(id){  //获取房屋是否已收藏的状态
      let res=await reqCheckIsCollected(id)
      if(res.status===400){//token过期
        Toast.fail(res.description,2,null,false)
        resetUserData()
        removeRecord()
        user_action.remove()
        return
      }
      setCollectState({active:false,isCollected:res.body.isFavorite})
    }
    async function collected(id){ //收藏房屋
      let res=await reqAddCollected(id)
      setCollectState({active:false,isCollected:true})
      Toast.success(res.description+'成功',2,()=>{},false)
    }
    async function cancelCollected(id){ //取消收藏房屋
      let res=await reqDeleteCollected(id)
      setCollectState({active:false,isCollected:false})
      Toast.success(res.description+'成功',2,()=>{},false)
    }
    if(!data){
      new Promise(async resolve=>{
        if(checkLogin())await checkIsCollected(id)
        getDetail(id)
        resolve()
      })
    }
    if(collectState.active)collectState.isCollected?cancelCollected(id):collected(id)
  },[data,id,collectState,user,props])

  return (
      data?<div className='detail-page'>

        <div className='detail-navbar'>
          <Navbar title={data.community}></Navbar>
        </div>
        
        <div className='detail-content'>
          <div className='carousel'>
            <Carousel 
            autoplay={true}
            infinite>
              {
                data.houseImg.map(i=> <img key={i} src={BASEURL+i} alt="" className='img'/>)
              }
            </Carousel>
          </div>

          <div className='detail-info'>
            <div className='title'>{data.title}</div>
            <div className='tags'>
              {
                data.tags.map(i=><Tag key={i} small>{i}</Tag>)
              }
            </div>

            <div className='message'>
              <div className='top'>
                <div className='price'><span><span>{data.price}</span>/月</span><span>租金</span></div>
                <div className='type'><span>{data.roomType}</span><span>房型</span></div>
                <div className='size'><span>{data.size}平米</span><span>面积</span></div>
              </div>
              <div className='bot'>
                <div className='finish'> <span>精修:</span> <span>精装</span> </div>
                <div className='orig'> <span>朝向:</span> <span>{data.oriented.join(',')}</span> </div>
                <div className='finish'> <span>楼层:</span> <span>{data.floor}</span> </div>
                <div className='finish'> <span>精修:</span> <span>普通住宅</span> </div>
              </div>
            </div>
          </div>

          <div className='location'>
            <div className='community'><span>小区:</span><span>{data.community}</span></div>
            <div className='map'>
              <Map 
                style={{height:'100%'}}
                center={window.BMapGL.Point(data.coord.longitude,data.coord.latitude)}
                zoom={18}
                enableScrollWheelZoom
              >
                <Marker
                  position={{lng:data.coord.longitude,lat:data.coord.latitude}}
                  autoViewport={true}
                  enableDragging={false}
                />
              </Map>
            </div>
          </div>

          <div className='mating'>
            <div className='title'>房屋配套</div>
            <div className='icons'>
              {
                data.supporting.length===0?<span>暂无数据</span>:
                data.supporting.map(i=>{
                  return<div className='icon-item' key={i}>
                    <i className={icons[i]}></i>
                    <span>{i}</span>
                  </div>
                })
              }
            </div>
          </div>

          <div className='condition'>
            <div className='title'>房源状况</div>
            <div className='content'>
              <img src={BASEURL+"/img/avatar.png"} alt="" />
              <div className='message'>
                <span>王女士</span>
                <span> <i className='iconfont icon-auth'></i> 已认证房主</span>
              </div>
              <div className='send'>发消息</div>
            </div>
            <div className='desc'>
              {
                data.description===''?<p>暂无房屋描述</p>:
                <p>{data.description}</p>
              }
            </div>
          </div>
          
          <div className='guess'>
            <div className='title'>猜你喜欢</div>
            <div className='list'>
              <HouseList list={guessData}></HouseList>
            </div>
          </div>
        </div>
        <div className='controller'>
            {
              controllers.map((i,index)=>{
                return <div key={i.id} className='item' style={i.style} onClick={()=>i.action()}>
                  {
                    i.icon?<i className={i.icon} style={index===0&&collectState.isCollected?{color:'#ff4f00'}:{}}></i>:null
                  }
                  <span>{i.name}</span>
                </div>
              })
            }
        </div>
      </div>:null
  )
})
